import { DataTypes } from 'sequelize';
import { sequelize } from '../config/database.js';

const Task = sequelize.define('Task', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  title: {
    type: DataTypes.STRING(200),
    allowNull: false,
    comment: '任务标题'
  },
  description: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: '任务详情（Markdown格式）'
  },
  is_completed: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    comment: '是否完成'
  },
  is_important: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    comment: '是否需要关注'
  },
  priority: {
    type: DataTypes.ENUM('low', 'medium', 'high'),
    defaultValue: 'medium',
    comment: '优先级'
  },
  completed_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '完成时间'
  },
  created_by: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '创建人ID'
  },
  updated_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '更新人ID'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'tasks',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_tasks_is_completed',
      fields: ['is_completed'],
    },
    {
      name: 'idx_tasks_is_important',
      fields: ['is_important'],
    },
    {
      name: 'idx_tasks_created_by',
      fields: ['created_by'],
    },
  ],
  hooks: {
    beforeUpdate: async (task) => {
      // 如果任务状态从未完成变为完成，设置完成时间
      if (task.changed('is_completed') && task.is_completed && !task.completed_at) {
        task.completed_at = new Date();
      }
      // 如果任务状态从完成变为未完成，清除完成时间
      if (task.changed('is_completed') && !task.is_completed && task.completed_at) {
        task.completed_at = null;
      }
    }
  }
});

// 实例方法
Task.prototype.toJSON = function() {
  const values = { ...this.get() };
  return values;
};

Task.prototype.markAsCompleted = async function(userId) {
  this.is_completed = true;
  this.completed_at = new Date();
  this.updated_by = userId;
  await this.save();
};

Task.prototype.markAsIncomplete = async function(userId) {
  this.is_completed = false;
  this.completed_at = null;
  this.updated_by = userId;
  await this.save();
};

// 类方法
Task.findByCreator = function(creatorId, options = {}) {
  return this.findAll({
    where: { created_by: creatorId },
    order: [['created_at', 'DESC']],
    ...options
  });
};

Task.findImportantTasks = function(options = {}) {
  return this.findAll({
    where: { 
      is_important: true,
      is_completed: false
    },
    order: [['created_at', 'DESC']],
    ...options
  });
};

Task.findPendingTasks = function(options = {}) {
  return this.findAll({
    where: { is_completed: false },
    order: [['created_at', 'DESC']],
    ...options
  });
};

Task.createTask = async function(taskData) {
  return await this.create(taskData);
};

Task.updateTask = async function(id, updateData, userId) {
  const task = await this.findByPk(id);
  if (!task) {
    throw new Error('任务不存在');
  }
  
  updateData.updated_by = userId;
  await task.update(updateData);
  return task;
};

export default Task;
